// 不做mysql , json
const fs = require('fs')
const Koa = require('koa')
const router = require('koa-router')();
const app = new Koa()
const mainData = require('./Data/mainData/MainData.json')
const classifyData = require('./Data/classifyData/classifyData.json')
const shopcarData = require('./Data/shopCarData/ShopCarData.json')  
const detailData = require('./Data/detailData/detailData.json')
const cors = require('koa2-cors')
const Mock = require('mockjs')
const path = require('path')
const Random = Mock.Random
const static = require('koa-static')

app.use(cors({
    origin: function (ctx) { //设置允许来自指定域名请求
        // if (ctx.url === '/test') {
        return '*'; // 允许来自所有域名请求
        // }
        // return 'http://localhost:3000'; //只允许http://localhost:8080这个域名的请求
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
}))
router.get('/home/main', async (ctx) => {
    ctx.response.body = {
        success: true,
        data: mainData
    }
})

router.get('/home/classify', async (ctx) => {
    ctx.body = {
        success: true,
        data: classifyData
    }
})

// 主页下方mock请求的数据
router.get('/home/list', async (ctx) => {
    let {
        limit = 20, page = 0
    } = ctx.request.query
    console.log(limit, page);
    // 参数 limit page
    //  http://localhost:9090/home/list?limit=20&page=1    qurrystring
    //  /detali/:123   param
    // to be continue 根据limit和page做数据筛选
    let data = Mock.mock({
        'list|20': [{
            "id": "@increment()",
            'title': '@ctitle(5,15)',
            "price": '@float(10, 1000, 1,1)',
            'imgsrc': Random.image('170x170')
        }]
    })
    ctx.body = {
        success: true,
        data
    }
})

router.get('/detail/:id', async (ctx) => {
    // console.log(ctx.params);
    const { id } = ctx.params;
    if (!id) {
        ctx.response.body = {
            success: false,
            mag: '请求数据'
        }
    }
    // to be continue
    ctx.response.body = {
        success: true,
        data: Mock.mock({
            id,
            title: '@ctitle(5, 10)',
            price: '@float(60, 1000, 0, 2)',
            rate: '@float(60, 100, 0, 1)',
            desc: '@csentence(6, 12)',
            attrValue: '@ctitle(2,6)'
        }), detailData
    }
})

router.get('/home/shop', async (ctx) => {
    ctx.body = {
        success: true,
        data: shopcarData
    }
})

// 启用服务器访问静态资源，
app.use(static(path.join(__dirname, "public")))

app
    .use(router.routes())
    .use(router.allowedMethods())

// 本地服务器
app.listen(9000, () => {
    console.log('server is running 9090')
})

// 上线服务器
// app.listen(9090, () => {
//     console.log('server is running 9090')
// })